package com.hzh.spark.core

import org.apache.spark.rdd.RDD
import org.apache.spark.util.LongAccumulator
import org.apache.spark.{SparkConf, SparkContext}

object Demo21Accumulator {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf()

    conf.setAppName("wordCount")
    conf.setMaster("local")

    val sc = new SparkContext(conf)

    val studentRDD: RDD[String] = sc.textFile("data/students.txt")

//    var count = 0
//    studentRDD.foreach(stu=>{
//      count += 1
//      println(count)
//    })
//    println (s"count:${count}")

    /**
     * 累加器
     */
    //1、定义一个累加器
    val accumulator: LongAccumulator = sc.longAccumulator

    studentRDD.foreach(stu=>{
      //2、对累加器进行累加
      accumulator.add(1)
    })
    //3、再从Driver端读取累加结果
    println(s"accumulator:${accumulator.value}")





  }
}
